
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "Common.hpp"

// ./client_udp serverip serverport
int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " serverip serverport" << std::endl;
        Die(ExitError::USAGE_ERR);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    // 1.创建socket
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "create socket error" << std::endl;
        exit(SOCKET_ERR);
    }

    // 1.1 填充server信息
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(serverport);
    server_addr.sin_addr.s_addr = ::inet_addr(serverip.c_str());

    int n = ::connect(sockfd, CONV(&server_addr), sizeof(server_addr));
    if (n < 0)
    {
        std::cout << "connect error" << std::endl;
        exit(CONNECT_ERR);
    }

    // 2. echo client
    std::string message;
    while(true)
    {
        char inbuffer[1024];
        std::cout << "Please Enter# ";
        std::getline(std::cin, message);

        n = ::write(sockfd, message.c_str(), message.size());
        if (n > 0)
        {
            int m = ::read(sockfd, inbuffer, sizeof(inbuffer));
            if(m > 0)
            {
                inbuffer[m] = 0;
                std::cout << inbuffer << std::endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }

    return 0;
}